import { provide, ref } from 'vue';
import { cloneDeep } from 'lodash';

export function useEvent({ canvasBtnEvent, updateDrawCanvas }) {
  const selectNode = ref(null);
  let controllNode = null;
  let aiShirtCanvas = null;
  let isMove = false;

  provide('activeSelectNode', selectNode);

  const initAIShirtCanvas = (asc) => {
    aiShirtCanvas = asc;
  };

  function touchStart(e) {
    // 获取点击坐标
    const touches = e.touches || [e];
    const touch = touches[0];

    const query = uni.createSelectorQuery();
    query
      .select('#controllCanvas')
      .boundingClientRect((rect: any) => {
        if (rect) {
          // 转换为相对于canvas的坐标
          const x = touch.clientX - rect.left;
          const y = touch.clientY - rect.top;

          // // console.log('点击位置:', x, y)

          // 检测点击的是哪个元素
          const clickedNode = aiShirtCanvas.getNodeAtPosition(x, y);
          // // console.log('点击的元素', clickedNode?._type, clickedNode)
          if (clickedNode?._type === 'btn') {
            controllNode = clickedNode;

            if (['scale', 'rotate'].includes(clickedNode.btnType)) {
              controllNode?.touchStart(e);
            } else {
              canvasBtnEvent(clickedNode);
            }
            return;
          }
          controllNode = null;

          if (clickedNode) {
            // 取消之前选中元素的选中状态
            if (selectNode.value && selectNode.value !== clickedNode) {
              selectNode.value.isSelected = false;
            }
            // 设置新选中的元素
            clickedNode.isSelected = true;
            selectNode.value = clickedNode;
            // aiShirtCanvas.draw();
            updateDrawCanvas();
          } else {
            updateSelectNode(null);
          }
          // 原有逻辑
          if (selectNode.value) {
            selectNode.value.touchStart(e);
          }
        }
      })
      .exec();
  }

  function touchMove(e) {
    console.log('touchMove')
    if (controllNode) {
      controllNode?.controllSapeNode(selectNode.value, e);
    } else {
      selectNode.value?.touchMove(e);
    }
    isMove = true;
    // aiShirtCanvas.draw()
    updateDrawCanvas();
  }

  function touchUp(e) {
    if (selectNode.value && isMove) {
      // 保存历史
      aiShirtCanvas.saveHistory();
      isMove = false;
    }

    controllNode = null;
    selectNode.value?.touchEnd(e);
    // aiShirtCanvas.draw()
    updateDrawCanvas();
  }

  /**
   * 更新选中元素
   * @param node
   */
  const updateSelectNode = (node) => {
    // if(node?.__id__ === selectNode.value?.__id) return;
    if (selectNode.value) {
      selectNode.value.isSelected = false;
    }
    // console.log('更新选中元素', cloneDeep(node));
    node && (node.isSelected = true);
    selectNode.value = node;
    // aiShirtCanvas.draw();
    updateDrawCanvas(false);
  };

  return {
    touchStart,
    touchMove,
    touchUp,
    selectNode,
    updateSelectNode,
    initAIShirtCanvas,
  };
}
